//
//  AppDelegate.m
//  FutureStar
//
//  Created by 李伟 on 2016/11/22.
//  Copyright © 2016年 liwei. All rights reserved.
//

#import "ZPAppDelegate.h"
#import "ZPAdvertiseView.h"
#import "ZPBaseTabBarController.h"
#import "ZPBaseNavigationController.h"
#import "ZPFirstStartViewController.h"
#import "ZPRegisterLoginViewController.h"
#import "ZPRegisterVerificationViewController.h"
#import "ZPRegisterSelectStuViewController.h"
#import "ZPRegisterInformationViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import <UMSocialCore/UMSocialCore.h>
#import <UShareUI/UMSocialUIManager.h>
@interface ZPAppDelegate ()

@property (nonatomic, strong)UIImageView *advertiseView;

@end

@implementation ZPAppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 0.启动时间
    sleep(1);
    
    // 1.创建窗口
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    // 2.把窗口设置为主窗口可见
    [self.window makeKeyAndVisible];
    
    // 3.设置状态栏
    application.statusBarStyle = UIStatusBarStyleLightContent;
    application.statusBarHidden =NO;
    
    //设置cookies
    [[ZPAuthEngine  sharedZPAuthEngine] registerAndSign];
    
    
    //推送
    //设置 AppKey 及 LaunchOptions
    [UMessage startWithAppkey:UMPushKEY launchOptions:launchOptions httpsenable:NO];
    //注册通知
    [UMessage registerForRemoteNotifications];
    //    [UMessage setLogEnabled:YES];
    //iOS10必须加下面这段代码。
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate=self;
        UNAuthorizationOptions types10=UNAuthorizationOptionBadge|UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
        [center requestAuthorizationWithOptions:types10 completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                //点击允许
                
            } else {
                //点击不允许
            }
        }];
    }
    
    
    // 4.程序开始启动,设置根视图
    [self startApplication];
    
    // 5.网络监测
    [self AFNetWorkingMonitoring];
    
    [[UMSocialManager defaultManager] setUmSocialAppkey:UMKEY];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:APP_WEIXIN_ID appSecret:APP_WEIXIN_SECRET redirectURL:nil];
    [UMSocialUIManager addCustomPlatformWithoutFilted:UMSocialPlatformType_UserDefine_Begin+2 withPlatformIcon:Z_IMAGE(@"copy") withPlatformName:@"复制链接"];
    
    return YES;
}

// 程序开始运行
- (void)startApplication
{
    // 3.2进入主程序界面主程序
    if ([[ZPAuthStore  sharedZPAuthStore] isLogin]) {
        self.window.rootViewController = [[ZPBaseTabBarController alloc] init];
    }else {
        ZPBaseNavigationController *registerLoginNvc = [[ZPBaseNavigationController alloc] initWithRootViewController:[[ZPRegisterLoginViewController alloc] init]];
        self.window.rootViewController = registerLoginNvc;
    }
    
//    // 3.设置根控制器
//    BOOL firstRun = [zUserDefaults boolForKey:@"firstLauch"];
//    if (firstRun == 0)
//    {
//        // 3.1 跳转新特性界面
//        [zUserDefaults setBool:YES forKey:@"firstLauch"];
//        self.window.rootViewController = [[ZPFirstStartViewController alloc] init];
//        
//    }
//    else
//    {
//        // 3.2进入主程序界面主程序
//        self.window.rootViewController = [[ZPBaseTabBarController alloc] init];
//        
//        
//        // 3.3进入注册登录界面
//        //        ZPBaseNavigationController *registerLoginNvc = [[ZPBaseNavigationController alloc] initWithRootViewController:[[ZPRegisterLoginViewController alloc] init]];
//        //        self.window.rootViewController = registerLoginNvc;
//        
//        
////        // 判断沙盒中是否存在广告图片，如果存在，直接显示
////        NSString *filePath = [self getFilePathWithImageName:[zUserDefaults valueForKey:adImageName]];
////        BOOL isExist = [self isFileExisWithFilePath:filePath];
////        
////        if (isExist) { // 图片存在
////            ZPAdvertiseView *advertiseView = [[ZPAdvertiseView alloc] initWithFrame:self.window.bounds];
////            advertiseView.filePath = filePath;
////            [advertiseView showAdvertiseView];
////        }
////        // 2.无论沙盒中是否存在广告图片，都需要重新调用广告接口，判断广告是否更新
////        [self getAdvertisingImage];
//    }
//    
//    //    [self startNetListen];
}


// 判断文件是否存在
- (BOOL)isFileExisWithFilePath:(NSString *)filePath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = FALSE;
    return [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
}


// 初始化广告页面
- (void)getAdvertisingImage
{
    // TODO 请求广告接口
    NSArray  *imageArray = zStartAdvertiseImage;
    NSString *imageUrl   = imageArray[arc4random() % imageArray.count];
    // 获取图片名
    NSArray *stringArr  = [imageUrl componentsSeparatedByString:@"/"];
    NSString *imageName = stringArr.lastObject;
    // 拼接沙盒路径
    NSString *filePath = [self getFilePathWithImageName:imageName];
    BOOL isExist = [self isFileExisWithFilePath:filePath];
    if (!isExist) {
        // 如果该图片不存在，则删除老图片，下载新图片
        [self downloadAdImageWithUrl:imageUrl imageName:imageName];
    }
}


// 下载新图片
- (void)downloadAdImageWithUrl:(NSString *)imageUrl imageName:(NSString *)imageName
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
        UIImage *image = [UIImage imageWithData:data];
        NSString *filePath = [self getFilePathWithImageName:imageName];
        // 保存文件的名称
        if ([UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES])
        {
            // 保存成功
            NSLog(@"保存成功");
            [self deleteOldImage];
            [zUserDefaults setValue:imageName forKey:adImageName];
            [zUserDefaults synchronize];
            // 如果有广告链接，将广告链接也保存下来
        } else {
            NSLog(@"保存失败");
        }
    });
}


// 删除旧图片
- (void)deleteOldImage
{
    NSString *imageName = [zUserDefaults valueForKey:adImageName];
    if (imageName)
    {
        NSString *filePath = [self getFilePathWithImageName:imageName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:filePath error:nil];
    }
}


// 根据图片名拼接文件路径
- (NSString *)getFilePathWithImageName:(NSString *)imageName
{
    if (imageName)
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
        return filePath;
    }
    return nil;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    //BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url options:options];
    if (!result) {
        if ([url.host isEqualToString:@"safepay"]) {
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url
                                                      standbyCallback:^(NSDictionary *resultDic) {
                                                          NSLog(@"result = %@",resultDic);
                                                          [[NSNotificationCenter defaultCenter]postNotificationName:@"AliPayResult" object:nil userInfo:resultDic];
                                                      }];
        }
    }else{
        [ZPPromptView showMessage:@"分享成功"];
    }

    
    return result;
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        if ([url.host isEqualToString:@"safepay"]) {
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url
                                                      standbyCallback:^(NSDictionary *resultDic) {
                                                          NSLog(@"result = %@",resultDic);
                                                          [[NSNotificationCenter defaultCenter]postNotificationName:@"AliPayResult" object:nil userInfo:resultDic];
                                                      }];
        }
    }else{
        [ZPPromptView showMessage:@"分享成功"];
    }
    return result;

}

#pragma mark - 推送回调
#pragma mark 推送回调函数
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    //关闭友盟自带的弹出框
    [UMessage setAutoAlert:NO];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
}

//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    if ([UIApplication sharedApplication].applicationIconBadgeNumber > 0) {
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    }
    
}


#pragma mark - <网络监测>
- (void)AFNetWorkingMonitoring
{
    NSURL *baseUrl = [NSURL URLWithString:@"www.baidu.com"];
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseUrl];
    NSOperationQueue *operationQueue = manager.operationQueue;
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:{
                self.isHasNetwork = YES;
                ZPLog(@"2/3/4G");
            }
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:{
                self.isHasNetwork = YES;
                ZPLog(@"WiFi");
            }
                [operationQueue setSuspended:NO]; // 线程不暂停
                break;
                
            case AFNetworkReachabilityStatusNotReachable:{
                self.isHasNetwork = NO;
                ZPLog(@"无网络");
            }
                break;
                
            default:{
                [operationQueue setSuspended:YES]; // 线程暂停
                ZPLog(@"default");
            }
                break;
        }
    }];
    // 开始网络监控
    [manager.reachabilityManager startMonitoring];
}





- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}


#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"FutureStar"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                     */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}

@end
